import { inject, InjectionKey, reactive } from 'vue'
import { SvgComponent, SvgState } from '../type'
import { cloneDeep } from 'lodash-es'

export const createSvgState = () => {
  const svgState: SvgState = reactive({
    baseConfig: {
      name: 'newIcon'
    },
    components: [],
    currentComponent: null,
    previewColor: '#1890ff'
  })
  return svgState
}

export const injectSvgStateKey: InjectionKey<SvgState> = Symbol('svg-state')

export const useSvgState = () => {
  const svgState = inject(injectSvgStateKey)!

  const setCurrentComponent = (component: SvgComponent) => {
    svgState.currentComponent = cloneDeep(component)
  }

  const addComponent = (component: SvgComponent) => {
    svgState.components.push(component)
  }

  const deleteComponent = (index: number) => {
    const { components, currentComponent } = svgState
    if (currentComponent && components[index].id === currentComponent.id) {
      svgState.currentComponent = null
    }
    components.splice(index, 1)
  }

  const saveComponent = () => {
    const { currentComponent } = svgState
    if (!currentComponent) return
    const index = svgState.components.findIndex(item => item.id === svgState.currentComponent!.id)
    index >= 0 && svgState.components.splice(index, 1, cloneDeep(currentComponent))
  }
  return {
    svgState,
    setCurrentComponent,
    addComponent,
    deleteComponent,
    saveComponent
  }
}
